// 基于准备好的dom，初始化echarts实例
var container = document.getElementById('deviceMap');
var URL = {
    "getNetworkGeoMap": contextPath + "/assetNetworkScreen/getNetworkGeoMap?code=",
    "getNetworkSummary": contextPath + "/assetNetworkScreen/getNetworkSummary?code=",
    "getNetworkTypeSummary": contextPath + "/assetNetworkScreen/getNetworkTypeSummary?code=",
    "getCodeName": contextPath + "/assetNetworkScreen/getCodeName?code=",
    "getProvOrgSummary": contextPath + "/assetNetworkScreen/getProvOrgSummary?code=",
    "getCityOrgSummary": contextPath + "/assetNetworkScreen/getCityOrgSummary?code=",
    "getCitys": contextPath + "/assetNetworkScreen/getCitys?code=",
    "getRecent7DaysAlarmSummary": contextPath + "/assetNetworkScreen/getRecent7DaysAlarmSummary?code=",
    "getRecent7DaysAlarm": contextPath + "/assetNetworkScreen/getRecent7DaysAlarm?code=",
    "getTypesCount": contextPath + "/assetNetworkScreen/getTypesCount?code=",
    "getAppSummary": contextPath + "/assetNetworkScreen/getAppSummary?code=",
    "reStat": contextPath + "/assetNetworkScreen/reStat?code=",
}

var PIC = {
    part_center: contextPath + '/page/adminSystem/index/bigScreen/navigation/two/img/part_center.png',
    part_flag: contextPath + '/page/adminSystem/index/bigScreen/navigation/two/img/part_flag.png',
    unpart_flag: contextPath + '/page/adminSystem/index/bigScreen/navigation/two/img/unpart_flag.png',
}

const width = container.scrollWidth;
const height = container.scrollHeight - 50;
const graph = new G6.TreeGraph({
    container: 'deviceMap',
    width: width,
    height: height,
    pixelRatio: 2,
    linkCenter: true,
    fitView: true,
    fitViewPadding: [100, 350, 50, 200],
    modes: {
        default: [{
            type: 'collapse-expand',
            onChange: function onChange(item, collapsed) {
                var data = item.get('model').data;
                data.collapsed = collapsed;
                return true;
            }
        }, 'drag-canvas', 'zoom-canvas']
    },
    defaultNode: {
        size: 16,
        anchorPoints: [[0, 0.5], [1, 0.5]],
        style: {
            fill: '#40a9ff',
            stroke: '#096dd9'
        }
    },
    defaultEdge: {
        shape: 'cubic-horizontal',
        style: {
            stroke: '#A3B1BF'
        }
    },
    layout: {
        type: 'mindmap',
        direction: 'H',
        getHeight: function getHeight() {
            return 16;
        },
        getWidth: function getWidth() {
            return 16;
        },
        getVGap: function getVGap() {
            return 10;
        },
        getHGap: function getHGap() {
            return 70;
        }
    }
});


graph.edge(function (node) {
    let newVar = nodeMap.get(node.target._cfg.id);
    // 1:绿色(交换机和防火墙都连通) 2:黄色(交换机和防火墙有一个处于连通) 3:红色(交换机和防火墙都不通) 4:无资产
    let color = 'green';
    if (newVar=== 1) {
        color = 'green';
    } else if (newVar=== 2) {
        color = 'yellow';
    } else if (newVar=== 3) {
        color = 'red';
    } else if (newVar=== 4) {
        color = 'gray';
    } else {
        color = 'green';
    }
    return {
        shape: 'cubic-horizontal',
        style: {
            stroke: color,
        },
    };
});

var centerX = 0;
var globalNodeId="";
graph.node(function (node) {
    if (node.id === globalNodeId) {
        centerX = node.x;
    }
    let pic = PIC.part_flag;
    if (node.root) {
        pic = PIC.part_center;
    }else {
        if (node.status === 4){
            pic = PIC.unpart_flag;
        }
    }
    let position=node.children && node.children.length > 0 ? 'left' : node.x > centerX ? 'right' : 'left';
    if (node.id === globalNodeId){
        position="bottom";
    }
    return {
        size: 26,
        label: node.name,
        img: pic,
        shape: 'image',
        labelCfg: {
            offset: 5,
            position:  position,
            style: {
                fill: '#84B1F3',

            }
        },

    };
});



function getCitys(params) {
    $.ajax({
        url: URL.getCitys + params,
        method: 'POST',
        dataType: 'json',
        async: false, // 设置为异步请求
        success: function (data) {
            let str = '';
            let paramCode = code;
            for (let i = 0; i < data.length; i++) {
                let datum = data[i];
                let cityCode = datum.id;
                if (i === 0) {
                    paramCode = cityCode
                    str += `<div class="cityname selectcity" data="${cityCode}"
                 style="background: url('${contextPath}/page/adminSystem/index/bigScreen/navigation/two/img/unSelect.png') no-repeat;background-position: center;margin: 8px auto;line-height: 55px;cursor: pointer;" >
                ${datum.name}
                </div>`
                } else {
                    str += ` <div class="cityname" data="${datum.id}"
                 style="background: url('${contextPath}/page/adminSystem/index/bigScreen/navigation/two/img/unSelect.png') no-repeat;background-position: center;margin: 8px auto;line-height: 55px;cursor: pointer;">
                ${datum.name}
            </div>`
                }
            }
            $(".citynames").html(str);
            localStorage.setItem('cityCode',paramCode);
            cityWeb(paramCode);

        }
    });
}

function cityWeb(params) {

    graph.data(datas(params));
    graph.render();
    graph.fitView();
}
function extractStatusMap(node, statusMap) {
    // 添加当前节点的数据到Map
    statusMap.set(node.id, node.status);

    // 递归处理子节点
    if (node.children && node.children.length > 0) {
        for (const childNode of node.children) {
            extractStatusMap(childNode, statusMap);
        }
    }
}

function datas(params) {
    let res = {}
    // 渲染左侧的结构
    $.ajax({
        url: URL.getCityOrgSummary + params,
        method: 'POST',
        dataType: 'json',
        async: false, // 设置为异步请求
        success: function (data) {
            if (data && data.list.length > 0) {
                res = data.list[0];
                nodeMap = new Map();
                extractStatusMap(res,nodeMap)
                globalNodeId=res['id']
            }
            $(".orgNum").html(data.total);
        }
    });
    return res;
}

function getTime(){

    let times=new Date();
    const weekDays = ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    const today = new Date();
    // 获取星期几
    const dayOfWeek = weekDays[today.getDay()];
    let date = times.getDate(), year = times.getFullYear(), month = times.getMonth(), hours = times.getHours(), min = times.getMinutes(), sec = times.getSeconds();
    let hss = isTwo(hours) + ':' + isTwo(min) + ':' + isTwo(sec);
    $('.hss').text(hss); $('.year').text(year); $('.monthdate').text(isTwo(month+1) + '-' + isTwo(date)); $('.week').text(dayOfWeek);
}

function isTwo(param){
    return String(param).length >= 2 ? param:'0'+param
}
$(function () {
    let code = localStorage.getItem('defCode');
    getCitys(code);
    $('.cityname').on('click', (e) => {
        let data = $(e.currentTarget).attr('data');
        $('.cityname').removeClass('selectcity');
        $(e.currentTarget).addClass('selectcity');
        localStorage.setItem('cityCode',data);
        cityWeb(data);
    });

    $('.jump').on('click', (e) => {
        $('.jump').css({background: '#0D1119', border: '1px solid #015B87'})
        $('.' + e.target.classList[1]).css({background: '#0060AA', border: '1px solid #0060AA'});
    });

    setInterval(function () {
        let code = localStorage.getItem('cityCode');
        cityWeb(code);
    }, 20000);
    getTime()
    setInterval(function(){
        getTime()
    },1000)

})
